package com.lyl.serurity.security;

import com.lyl.commonutils.JwtUtils;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * token管理
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Component
public class TokenManager {

    // 过期时间
    private long tokenExpiration = 24*60*60*1000;
    private String tokenSignKey = "zxjy";

    public String createToken(String username,Long id) {
        String token = Jwts.builder()
                .setSubject(username) .claim("username", username)
                .claim("id", id)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP).compact();

//        // 生成jwt
//        String token = JwtUtils.getJwtToken(id+"",username);

        return token;
    }

    public String getUserFromToken(String token) {
        String user = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        return user;
    }

    public Long getUserIdFromToken(String token,String filedName) {
        if(StringUtils.isEmpty(token)) return -1L;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (Long)claims.get(filedName);
    }

    // 删除token
    public void removeToken(String token) {

        //jwttoken无需删除，客户端扔掉即可。
    }

}
